<?php

/**
 * LoginForm class.
 * LoginForm is the data structure for keeping
 * user login form data. It is used by the 'login' action of 'SiteController'.
 */
class SignUpForm extends CFormModel {

    public $email;
    public $email_r;
    public $password;
    public $password_r;
    public $accept;

    /**
     * Declares the validation rules.
     * The rules state that username and password are required,
     * and password needs to be authenticated.
     */
    public function rules() {
        return array(
// username and password are required
            array('email, email_r, password, password_r, accept', 'required'),
            array('email', 'CheckMailExist'),
            array('email, email_r', 'email'),
            // rememberMe needs to be a boolean
            array('accept', 'checkAccept'),
            // password needs to be authenticated
            array('email_r', 'compare', 'compareAttribute' => 'email'),
            array('password_r', 'compare', 'compareAttribute' => 'password'),
        );
    }

    /**
     * Declares attribute labels.
     */
    public function attributeLabels() {
        return array(
            'accept' => 'Tôi đã đọc và chấp nhận các điều khoản.',
            'email' => 'Email',
            'email_r' => 'Email nhập lại',
            'password' => 'Password',
            'password_r' => 'Password nhập lại'
        );
    }

    public function checkAccept() {
        if ($this->accept == 0) {
            $this->addError('accept', 'Bạn phải chấp nhận các điều khoản');
        }
    }

    public function Register() {
        if (NguoiDungService::addNguoiDung($this->email, $this->password)) {
            return TRUE;
        }
        return FALSE;
    }

    public function Login() {
//        try {
            $auth = new UserIdentity($this->email, $this->password);
            $auth->authenticate();
            $duration = 0; // 30 days
            Yii::app()->user->login($auth, $duration);
            return true;
//        } 
//        catch (Exception $ex) {
//            return FALSE;
//        }
    }

    public function CheckMailExist() {
        if (NguoiDungService::checkMailExist($this->email)) {
            $this->addError('email', 'Email đã đăng kí');
        }
    }

}
